package oop.db.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import oop.data.Question;
import oop.data.SimpleCategory;
import oop.data.SimpleUser;
import oop.db.Database;

public class QuestionDAO {

	public static List<Question> fetchBySection(long sectionId) throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String sql = "SELECT tblQuestion.ques_id, ques_content, ques_level, "
					+ "cat_id, cat_name, ques_author, user_name, mark, sect_id "
					+ "FROM tblQuestion, tblSectionQuestion, tblCategory, tblUser "
					+ "WHERE tblQuestion.ques_id = tblSectionQuestion.ques_id "
					+ "AND ques_author = user_id "
					+ "AND ques_category = cat_id "
					+ "AND sect_id = ?";
	
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, sectionId);
			rs = stmt.executeQuery();
			return fromResultSet(rs);
		} finally {
			if (rs != null)	rs.close();
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}
	
	public static List<Question> fetchByCategoryNotInSectionRandomly(long categoryId, long sectionId, int quantity) throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String sql = "SELECT tblQuestion.ques_id, ques_content, ques_level, " +
					"cat_id, cat_name, ques_author, user_name, mark, sect_id " +
					"FROM tblQuestion " +
					"WHERE (ques_id NOT IN (" +
								"SELECT ques_id " +
								"FROM tblSectionQuestion " +
								"WHERE sect_id = ?) ) " +
							"AND ques_category = ? " +
					"ORDER BY RAND() " +
					"LIMIT 0, ?";
			
			conn = Database.get().getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setLong(1, sectionId);
			stmt.setLong(2, categoryId);
			stmt.setInt(3, quantity);
			rs = stmt.executeQuery();
			return fromResultSet(rs);
		} finally {
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

	private static List<Question> fromResultSet(ResultSet rs)
			throws SQLException {
		List<Question> questions = new ArrayList<Question>();
		while (rs.next()) {
			questions.add(new Question(rs.getInt(1), rs.getString(2), rs
					.getInt(3), new SimpleCategory(rs.getInt(4), rs
					.getString(5)), new SimpleUser(rs.getInt(6), rs
					.getString(7)), rs.getLong(9), rs.getDouble(8)));
		}
		return questions;
	}

}
